<?php
namespace api\models;

use api\models\base\BaseForm;
use common\models\Active;
use common\models\Question;

/**
 * 活动商品 逻辑层
 */
class QuestionForm extends BaseForm
{

    // 设置问题
    public function setQuestion( $aid, $uid, $ip )
    {
        $ret2question = $this->getQuestion( $aid );
        if( !$ret2question[ 'status' ] ){ return $ret2question; }

        $question_info = $ret2question[ 'data' ];

        // 提取出来有效的问答数据
        for ($i = 1; $i <= 10; $i++) {
            if (isset($question_info['ask' . $i])
                && isset($question_info['answer' . $i])
                && $question_info['ask' . $i]
                && $question_info['answer' . $i]
            ) {
                $ask_list[] = $question_info['ask' . $i];
                $answer_list[] = $question_info['answer' . $i];
            }
        }

        // 随机抽取最多4个问答选项
        $count = count($answer_list);
        if ($count > 4) { $count = 4; }

        $question_data = array();
        while (count($question_data) < $count) {
            $i = rand(0, count($answer_list) - 1);
            $question_data[$i] = $i;
        }

        $datalist_ask = $datalist_answer = array();
        foreach ($question_data as $d) {
            $datalist_ask[] = $ask_list[$d];
            $datalist_answer[] = $answer_list[$d];
        }

        // 从选项中随机抽取一个作为问题和正确答案
        $i = rand(0, $count - 1);
        $ask = $datalist_ask[$i];
        $answer = $datalist_answer[$i];

        $question_info = [
            'aid' => $aid,
            'id' => $question_info['id'],
            'ask' => $ask,
            'answer' => $answer,
            'datalist' => $datalist_answer,
            'title' => $question_info['title'],
            'uid' => $uid,
            'ip' => $ip,
            'now' => time()
        ];

        $sign = $this->rc_encrypt( $question_info,'E' );

        $result2question = [
            'sign' => $sign,
            'ask' => $ask,
            'datalist' => $datalist_answer,
            'title' => $question_info['title'],
        ];

        return [
            'status' => true,
            'msg' => '查询成功',
            'data' => $result2question
        ];
    }

    // 获取问题
    private function getQuestion( $aid )
    {
        $ret2return = [ 'status' => false, 'msg' => '没有设置问答信息', 'error_code' => 201 ];

        $question_info_json = \Yii::$app->redis->get( 'question_info' );
        $question_info = json_decode( $question_info_json, true );
        if( !$question_info ){
            $question_info = Question::find()
                ->where( [ 'active_id' => $aid, 'sys_status' => 0  ] )
                ->limit( 1 )
                ->asArray()->one();

            \Yii::$app->redis->set( 'question_info', json_encode( $question_info ) );
        }

        if( !$question_info ){ return $question_info; }

        return [
            'status' => true,
            'msg' => '查询成功',
            'data' => $question_info
        ];
    }
}
